package com.carqueue.utils;/*
 * @author 86136
 * @create 2023/8/17 15:47
 */

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.*;

public class JWTUtils {

    private static final String PRIVATE_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";

    private static final String ISS = "carqueue";

    private static final long EXPIRATION_ONE_WEEK = 604800000L;

    /**
     * @param info={username,id}
     * @return JWT
     */
    public static String createToken(List<String> info) {

        // HEADER
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        Map<String, Object> claims = new HashMap<>();

        // PAYLOAD
        claims.put("username", info.get(0));
        claims.put("id", info.get(1));

        JwtBuilder jwt = Jwts.builder()
                .setIssuer(ISS)
                .setHeader(header)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_ONE_WEEK))
                .signWith(SignatureAlgorithm.HS256, PRIVATE_KEY);

        return jwt.compact();
    }

    /**
     * 验证Token，返回数据只有id和account和type的User对象
     *
     * @param JWT=String
     * @return {username,id}/null
     */
    public static List<String> checkToken(String JWT) {

        Claims claims = getClaimsFromToken(JWT);

        if (claims == null) {
            return null;
        }

        String username = (String) claims.get("username");
        String id = (String) claims.get("id");

        List<String> info = new LinkedList<>();
        info.add(username);
        info.add(id);

        return info;
    }

    /**
     * 获取有效载荷
     *
     * @param token
     * @return
     */
    public static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(PRIVATE_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
        return claims;
    }
}
